package com.example.trackcircuitdiagnosis.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cc
 * @data 2021年06月28日 23:34
 */
public class TokenUtil {

    //自定义密钥
    private static String secretKey = "mysecret";
    //签发者
    private static String ITYZ_KEY = "ityz_jwt_token";

    /**
     * 生成签名
     */
    public static String getToken(String userId){
        //获取密钥
        Algorithm algorithm = getAlgorithm();
        //添加自定义信息
        Map map = new HashMap();
        map.put("userId", userId);
        //设置keyId
        String keyId =  "cc"+userId;
        String token = JWT.create()
                //.withIssuedAt(now)//当前时间
                //.withExpiresAt(expiresDate)//过期时间
                .withKeyId(keyId)
                .withIssuer(ITYZ_KEY)//签发者
                .withHeader(map)//自定义信息
                .sign(algorithm);//密钥
        return token;
    }

    /**
     * 解析签名
     * @author ityz
     */
    public static String parseToken(String token){
        String msg = null;
        //获取密钥
        Algorithm algorithm = getAlgorithm();
        JWTVerifier jwtVerifier = JWT.require(algorithm)
                .withIssuer(ITYZ_KEY)//签发者
                .build();

        DecodedJWT jwt = jwtVerifier.verify(token);
        String userId = jwt.getHeaderClaim("userId").as(String.class);
        return userId;
    }

    /**
     * 获取自定义密钥
     * @author ityz
     */
    private static Algorithm getAlgorithm(){
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        return algorithm;
    }
}